import { http } from '@kit.NetworkKit';
import { AuthInfo } from '../beans/Infos';
import { JSONObject } from '../beans/JSONObject';

export default class AuthManager {
  static token: string
  static accessToken: string

  private static instance: AuthManager;

  // 私有构造函数，防止外部通过 new 创建实例
  private constructor() {}

  // 静态方法，用于获取单例实例
  public static getInstance(): AuthManager {
    if (!AuthManager.instance) {
      AuthManager.instance = new AuthManager();
    }
    return AuthManager.instance;
  }

  private static async getToken() {
    // 每一个httpRequest对应一个HTTP请求任务，不可复用
    let httpRequest = http.createHttp();
    const url = "https://connect-drcn.dbankcloud.cn/agc/apigw/oauth2/v1/token"
    const jsonStr = "{\n" +
      "   \"useJwt\":\"1\",\n" +
      "   \"grant_type\":\"client_credentials\",\n" +
      `   "client_id":"${AuthInfo.clientID}",\n` +
      `   "client_secret":"${AuthInfo.clientSecret}"\n` +
      "}"
    let data: http.HttpResponse
    try {
      data = await httpRequest.request(
        // 填写HTTP请求的URL地址，可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
        url,
        {
          method: http.RequestMethod.POST,
          extraData: jsonStr,
          header: {
            'Content-Type': 'application/json'
          },
        })
    } catch (err) {
      console.error('error:' + JSON.stringify(err));
      return Promise.reject()
    }
    const rawJson: JSONObject = JSON.parse(data!.result as string)
    AuthManager.token = rawJson.access_token as string
    httpRequest.destroy();
    return Promise.resolve()
  }

  private static async login() {
    // 每一个httpRequest对应一个HTTP请求任务，不可复用
    let httpRequest = http.createHttp();
    const url = `https://connect-drcn.dbankcloud.cn/agc/apigw/oauth2/third/v1/user-signin?productId=${AuthInfo.productID}`
    const jsonStr = "{\n" +
      "    \"provider\": 0,\n" +
      `    "token": "${AuthInfo.phone}",\n` +
      "    \"useJwt\": 1\n" +
      "}"
    let data: http.HttpResponse
    try {
      data = await httpRequest.request(
        // 填写HTTP请求的URL地址，可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
        url,
        {
          method: http.RequestMethod.POST,
          extraData: jsonStr,
          header: {
            'Content-Type': 'application/json',
            "Authorization": "Bearer " + AuthManager.token,
            "client_id": AuthInfo.clientID
          },

        })
    } catch (err) {
      console.error('error:' + JSON.stringify(err));
      return Promise.reject()
    }
    const rawJson: JSONObject = JSON.parse(data!.result as string)
    const accessToken = rawJson.accessToken as JSONObject
    AuthManager.accessToken = accessToken.token as string
    httpRequest.destroy()
    return Promise.resolve()
  }

  static async init() {
    await AuthManager.getToken()
    await AuthManager.login()
  }
}